<!--
 * @Description:
 * @Version: 0.1
 * @Author: EveChee
 * @Date: 2020-05-27 09:46:01
 * @LastEditTime: 2021-01-29 19:13:02
-->
<template>
    <div class="side-bar" :class="{ collapse }">
        <el-menu
            class="sidebar-menu"
            :default-active="activeMenu"
            :background-color="variables.menuBg"
            :text-color="variables.menuText"
            :unique-opened="true"
            :active-text-color="variables.menuActiveText"
            :collapse="collapse"
            :collapse-transition="false"
            @select="selMenu"
            @open="openMenu"
            mode="vertical"
        >
            <SideBarItem v-for="(nav, i) in navData" :key="i" :item="nav" />
        </el-menu>
    </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Component, Emit, Prop, PropSync } from 'vue-property-decorator'
import SideBarItem from './SideBarItem.vue'
import { getUrlSlice } from '@/utils'
import SSpa from '@/sspa'
const sSpa = new SSpa()
@Component({
    components: { SideBarItem },
})
export default class SideBar extends Vue {
    @Prop()
    collapse!: boolean
    // 临时数据
    @PropSync('routes', {
        default: () => [],
    })
    innerRoutes!: any
    showLogo = false
    mounted() {
        const mfeMainDOM: any = document.getElementById('mfe-main')
        sSpa.register('safeguard-admin', {
            parent: mfeMainDOM,
            keepAlive: true,
        })
        sSpa.register('dealer-admin', { parent: mfeMainDOM, keepAlive: true })
        sSpa.register('fx110-app-admin', {
            parent: mfeMainDOM,
            keepAlive: true,
        })
        sSpa.eventBus.register('menuEvent', this.mfeEmit)
        this.navData = this.createNav()
    }

    mfeEmit({ name, routes }: { name: string; routes: any[] }) {
        if (!routes?.length) {
            // 没有路由发送 return掉  是否关闭loading????待定
            return
        }
        this.addRoutesToMenu(name, routes)
        this.navData = this.createNav()
    }
    addRoutesToMenu(name, routes) {
        const data = this.innerRoutes.find(({ path }) => path === `/${name}`)
        if (!data) {
            return
        }
        data.children = routes
        this.$set(this.appInfoGeted, name, true)
    }
    variables = {
        menuBg: '#304156',
        menuText: '#bfcbd9',
        menuActiveText: '#409EFF',
    }

    parseRouteForBar(r: any, basePath = '/') {
        const nav: Array<NavData> = []
        r.forEach(({ meta, path, children }: any) => {
            const mpath = this.pathResolve(basePath, path)
            if (meta?.inTheBar || (children && children.length)) {
                const obj: NavData = {
                    subName: meta?.title,
                    path: mpath,
                    icon: meta?.icon,
                    lazy: !!meta.lazy,
                    loading: false,
                }
                if (children?.length) {
                    obj.children = this.parseRouteForBar(children, obj.path)
                }
                nav.push(obj)
            }
        })
        return nav.filter(({ subName }) => !!subName)
    }

    pathResolve(basePath: string, path: string) {
        if (basePath === '/') {
            return path.indexOf('/') !== 0 ? basePath + path : path
        }
        const hasHash = basePath.indexOf('#') !== -1
        const concat = hasHash ? '/' : '#'
        // 子应用哈希路由
        return basePath + concat + path
    }

    navData: Array<NavData> = []
    createNav() {
        return this.parseRouteForBar(this.innerRoutes)
    }

    get activeMenu() {
        return (this as any).$route?.fullPath.split('?')[0]
    }
    appInfoGeted: any = {} // 已加载的应用
    // // 点击菜单
    selMenu(index: string, indexPath: any[]) {
        // index && this.$router.push(index)
        const url = `${location.origin}${index}`
        index && history.pushState({ url: url }, '', url)
    }
    openMenu(index: string, indexPath: any[]) {
        const URLS = getUrlSlice(index) ?? []
        const APP_NAME = URLS[0]
        if (!APP_NAME || this.appInfoGeted[APP_NAME]) {
            return
        }
        // 唤醒子应用 子应用去拿到菜单 返送回来  并清除lazy 改变当前的子菜单
        const now = this.navData.find(
            ({ path }) => path === indexPath[indexPath.length - 1]
        )
        now && Reflect.set(now, 'loading', true)
        this.changeContainer(APP_NAME)
        this.$router.push({ path: `${APP_NAME}` })
    }
    @Emit('new-container')
    changeContainer(id: string) {
        return id
    }
}

export interface NavData {
    // 应用名
    // appName?: string
    // 导航标题
    subName: string
    // 子项
    children?: Array<NavData>
    // 路由
    path: string
    // 图标
    icon?: string
    // 是否不需要自动路由跳转
    lazy?: boolean
    loading?: boolean
}
</script>

<style scoped lang="less">
.side-bar {
    height: 100%;
    background: #304156;
    padding: 20px 0;
    box-sizing: border-box;
    width: 210px;
    transition: width 0.28s;
    &.collapse {
        width: auto !important;
    }
    .sidebar-menu {
        height: 100%;
        border: none;
    }
}
</style>
